#include "st_responder.h"

int main()
{
	SESSION_LIST current_session;
	USER_DATA user_info;
		
	FILE *html_file;
	char get_char;
	char html_cache[PAGE_SIZE_];
	UINT_ i;
	
	char *get_data;
	UINT_ session_id;
	HTML_OP get_op;
	BOOL_ logined;
	
	DB_LINKER db_linker;
	
	/*init*/
	/*session init*/
	session_Create(&current_session,sizeof(USER_DATA));
	/*read main page from file*/
	
	html_file=fopen("index","r");
	if(html_file==NULL)
	{
		show_Error();
		return 1;
	};
	i=0;
	for(get_char=fgetc(html_file);get_char!=EOF;get_char=fgetc(html_file))
	{
		html_cache[i]=get_char;
		++i;
	};
	fclose(html_file);
	
	html_cache[i]='\0';
	
	/*start link the database*/
	
	if(db_Connect(&db_linker,DB_USER,DB_PAS,DB_HOST,DATABASE_NAME_)==NULL)
	{
		show_Error();
		return 1;
	};
	
	while(FCGI_Accept()>=0)
	{
		/*get login info*/
		logined=(login_Check(&user_info,&current_session)==NULL?FALSE_:TRUE_);
		
		/*now start the command check*/
		get_data=getenv("QUERY_STRING");
				
		if(get_data==NULL)
		{
			if(!logined)
			{
				show_Login(html_cache);
			}
			else
			{
				show_Main(html_cache,&user_info);
			};
			continue;
			
		}
		else
		{
			/*start command check*/
			op_Get(&get_op,get_data);
			if(get_op.type==NONE)
			{
				if(!logined)
				{
					show_Login(html_cache);
				}
				else
				{
					show_Main(html_cache,&user_info);
				};
				continue;
			}
			else if(get_op.type==LOGIN)
			{
				if(user_Check(&user_info,&db_linker)!=NULL)
				{				
				session_id=session_Append(&user_info,&current_session);
								
				printf("Set-Cookie: user=%s;\n",user_info.user_id);
				printf("Set-Cookie: id=%ld;\n",session_id);
				
				show_Main(html_cache,&user_info);
				}
				else
				{
					show_Login(html_cache);
				};
				continue;
			}
			else if(get_op.type==LOGOUT)
			{
				if(!logined)
				{
					show_Login(html_cache);
				}
				else
				{
					session_Remove(&user_info,&current_session);
					
					printf("Set-Cookie: user=0;\n");
					printf("Set-Cookie: id=0;\n");
					
					show_Login(html_cache);
				};
				continue;
			}
			else if(get_op.type==INFO)
			{
				if(!logined)
				{
					show_Login(html_cache);
				}
				else
				{
					show_Info(html_cache,&user_info,&db_linker);
				};
				continue;
			}
			else if(get_op.type==NEWS)
			{
				if(!logined)
				{
					show_Login(html_cache);
				}
				else
				{
					show_Error();
				};
				continue;
			}
			else if(get_op.type==SCORE)
			{
				if(!logined)
				{
					show_Login(html_cache);
				}
				else
				{
					show_Score(html_cache,&user_info,&get_op,&db_linker);
				};
				continue;
			}
			else
			{
				show_Error();
				continue;
			};
		};
				
	};
	session_Drop(&current_session);
	return 0;
};
